<?php
require 'ScrapperHelper.php';

/**
 * Scrapper class
 *
 * @author Endel
 */
class Scrapper {

	public static $MATCH_ALL = 0;
	public static $MATCH_SINGLE = 1;

	private $matches;

	private $debug = false;

	private $base_url;
	private $current_page;
	private $pages = array();
	
	private $curl;

	public function Scrapper($base_url) {
		$this->base_url = $base_url;
		$this->page($this->base_url);
	}

	public function get_matches() {
		return $this->matches;
	}

	public function page($relative_url) {
		$this->current_page = $relative_url;
		return $this->pages[$this->current_page] = $this->browse( $this->current_page );
	}

	public function scrap($pattern, $match, $filter = false) {
		if ($match == self::$MATCH_ALL) {
			preg_match_all($pattern, $this->pages[$this->current_page], $matches);
		} else {
			preg_match($pattern, $this->pages[$this->current_page], $matches);
		}

		return ($filter) ? $matches[0] : $matches;
	}

	public function extract($subject, $method) {
		$extracted = "";
		if (method_exists(ScrapperHelper, $method)) {
			$extracted = ScrapperHelper::$method($subject);
		} elseif (function_exists($method)) {
			$extracted = $method($subject);
		} else {
			return "You must declare {$method} function.";
		}
		return $extracted;
	}

	public function get_url($url) {
		return $this->base_url . $url;
	}

	private function browse($url) {
		$url = $this->get_url($url);
		
		$this->print_debug('Browsing', $url);
		
		$this->curl = curl_init();
		curl_setopt ($this->curl, CURLOPT_URL, $url);
		//curl_setopt ($ch, CURLOPT_USERAGENT, $s_user_agent);
		curl_setopt ($this->curl, CURLOPT_RETURNTRANSFER, 1);
		$content = curl_exec ($this->curl);
		curl_close ($this->curl);
		
		return $content;
	}

	private function print_debug($title, $message) {
		if ($this->debug)
			print "<br /><br /><strong>$title</strong> $message<br /><br />";
	}
	
}


?>
